package com.jwong.grpc.jwtauth;

import com.jwong.grpc.helloworld.GreeterGrpc;
import com.jwong.grpc.helloworld.HelloReply;
import com.jwong.grpc.helloworld.HelloRequest;
import io.grpc.CallCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 向 AuthServer 请求greeting的身份验证客户端。
 */
public class AuthClient {

  private static final Logger logger = Logger.getLogger(AuthClient.class.getName());

  private final ManagedChannel channel;
  private final GreeterGrpc.GreeterBlockingStub blockingStub;
  private final CallCredentials callCredentials;

  /**
   * 构造访问 GreeterGrpc 服务器的客户端。
   */
  AuthClient(CallCredentials callCredentials, String host, int port) {
    this(
        callCredentials,
        ManagedChannelBuilder
            .forAddress(host, port)
            // 默认情况下，通道是安全的（通过 SSLTLS）。
            // 对于此示例，我们禁用 TLS 以避免需要证书，但建议在传递凭据时使用安全通道。
            .usePlaintext()
            .build());
  }

  /**
   * 使用现有通道构造访问 GreeterGrpc 服务器的客户端。
   */
  AuthClient(CallCredentials callCredentials, ManagedChannel channel) {
    this.callCredentials = callCredentials;
    this.channel = channel;
    this.blockingStub = GreeterGrpc.newBlockingStub(channel);
  }

  public void shutdown() throws InterruptedException {
    channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
  }

  public String greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();

    // 使用应用了给定调用凭据的存根来调用 RPC。
    HelloReply response =
        blockingStub
            .withCallCredentials(callCredentials)
            .sayHello(request);

    logger.info("Greeting: " + response.getMessage());
    return response.getMessage();
  }

  public static void main(String[] args) throws Exception {

    String host = "localhost";
    int port = 9000;
    String user = "world";
    String clientId = "default-client";

    CallCredentials credentials = new JwtCredential(clientId);
    AuthClient client = new AuthClient(credentials, host, port);

    try {
      client.greet(user);
    } finally {
      client.shutdown();
    }
  }
}
